<?php
namespace Admin\Logic;
use \Think\Model;
class UserLogic extends Model{
	
	protected $tableName	= 'user';
	protected $fields 		= array('id', 'username', 'password', 'is_active', 'role_id', 'last_ip', 'before_ip', 'create_time', 'login_time',
									'_type'=>array('id'=>'int','username'=>'varchar','password'=>'char','is_active'=>'tinyint','role_id'=>'int','last_ip'=>'varchar','before_ip'=>'varchar','create_time'=>'int','login_time'=>'int')
									);
	protected $_validate 	= array(
									array('username','require','帐号名不能为空！'),	
									array('username','','该角色已经存在！',0,'unique',1), // 在新增的时候验证username字段是否唯一
									array('username','checkName','不存在该帐号或帐号已被禁用',1,'callback',4),  // 只在登录时候验证帐号是否存在
									array('password','require','密码不能为空！',0,'',1),
									array('password','checkPwd','密码错误！',1,'callback',4), // 只在登录时候验证帐号密码是否正确
									array('chkpw','password','确认密码不正确',0,'confirm'), // 验证确认密码是否和密码一致
									);	
	protected $_auto 		= array ( 
									array('password','',2,'ignore'),
									array('password','md5',3,'function') , // 对password字段在新增和编辑的时候使md5函数处理
									array('is_active','1'),  // 新增的时候把is_active字段设置为1
									);									

	//获取总页数
	public function getPageCount(){
		
		$count      = M($this->tableName)->count();
		return	$count;
	}									
									
	/*
	 * 获取分页
	 * pageRows		每页显示行数
	 */	
	public function getPage($pageRows=10){
		
		$count		= $this->getPageCount();
		$Page       = new \Lib\Page\Ws_page($count,$pageRows);
		return	$Page->show();		
	}

	/*
	 * 获取指定行内容
	 * pageRows		每页显示行数,为0表示全读出来
	 * currPage		当前页页数
	 * condition	过滤条件，以数组形式
	 */
	public function getList($pageRows=0,$currPage=1,$condition=array()){
		
		if($pageRows){
			return	M($this->tableName)->where($condition)->order('id desc')->page($currPage.','.$pageRows)->select();
		}
		else{
			return	M($this->tableName)->select();
		}
	}	

	/*
	 * 获取权限详细内容
	 * datatable		数据源
	 */	
	public function getRoleDetail($datatable){
		
		$Role		= D('Role','Logic');	
		foreach($datatable as $w => $v){
			if($v['role_id']>0){
				$datatable[$w]['RoleName']	= $Role->getRoleName($v['role_id']);
			}
		}
		return $datatable;
	}	

	/*
	 * 查找用户名是否存在
	 * username		用户名
	 */		
	protected function checkName($username=''){
		$username		= $username == '' ? I('get.username') : $username;
		$row			= M($this->tableName)->getByUsername($username);
		if(intval($row['is_active'])>0){
			return	$row['id'];
		}
		else{
			return	false;
		}
	}
	
	/*
	 * 查找用户名密码是否正确
	 * username		用户名
	 * password		密码
	 */		
	protected function checkPwd($password='',$username=''){
		$password		= $password == '' ? md5(I('get.password')) : md5($password);
		$username		= $username == '' ? I('get.username') : $username;
		
		$row			= M($this->tableName)->where(" username='$username' and password='$password' ")->cache($username.$password,10)->find();
		if($row){
			return	$row['id'];
		}
		else{
			return	false;
		}
	}	
}
